<?php

namespace Biz\service\Store;


use Biz\model\brand\CustomCategoryWiki as mCustomCategoryWiki;
use Biz\model\store\StoreCustomCategoryWiki;
use Biz\model\wiki\Wiki as mWiki;
use Biz\model\wiki\WikiBasic as mWikiBasic;
use Biz\module\Classes\wiki\Infos;
use Biz\service\wiki\Wiki;

class CustomCategoryWikiService
{
    /**
     * 删除分类商品
     * @param int $categoryId
     * @param int $basicId
     * @param int $storeId
     * @return bool
     */
    public static function delCategoryWiki(int $categoryId, int $basicId, int $storeId): bool
    {
        return StoreCustomCategoryWiki::updateData(['custom_state' => StoreCustomCategoryWiki::STATE_CANCEL],
            ['category_id' => $categoryId, 'basic_id' => $basicId, 'store_id' => $storeId]);
    }

    /**
     * 编辑分类商品
     * @param int $categoryId
     * @param $data
     * @param int $storeId
     * @return bool
     */
    public static function editCategoryWiki(int $categoryId, $data, int $storeId): bool
    {
        $data = json_decode($data, true);
        $basicList = StoreCustomCategoryWiki::selectByWhere(['category_id' => $categoryId, 'store_id' => $storeId]);
        $basicIds = array_column($basicList, 'basic_id');
        $dataWikiIds = array_column($data, 'basic_id');
        $delWikiIds = array_diff($basicIds, $dataWikiIds);
        if ($delWikiIds) {
            StoreCustomCategoryWiki::updateData(['custom_state' => StoreCustomCategoryWiki::STATE_CANCEL],
                ['category_id' => $categoryId, 'basic_id' => $delWikiIds, 'store_id' => $storeId]);
        }
        foreach ($data as $row) {
            if (in_array($row['basic_id'], $basicIds)) {
                StoreCustomCategoryWiki::updateData([
                    'sort' => $row['sort'],
                    'custom_state' => StoreCustomCategoryWiki::STATE_NORMAL,
                ], ['category_id' => $categoryId, 'basic_id' => $row['basic_id'], 'store_id' => $storeId]);
            } else {
                StoreCustomCategoryWiki::insertData([
                    'category_id' => $categoryId,
                    'store_id' => $storeId,
                    'basic_id' => $row['basic_id'],
                    'sort' => $row['sort'],
                ]);
            }
        }

        return true;
    }

    /**
     * 获取商品列表
     * @param int $storeId
     * @param int $categoryId
     * @return array
     */
    public static function bGetCategoryWikiList(int $storeId, int $categoryId = 0): array
    {
        $result = [];
        $categoryWikiList = StoreCustomCategoryWiki::selectByWhere([
            'category_id' => $categoryId,
            'store_id' => $storeId,
            'custom_state' => StoreCustomCategoryWiki::STATE_NORMAL,
            'ORDER' => ['sort' => 'ASC', 'id' => 'DESC'],
        ]);
        $basicWikiList = mWikiBasic::selectByWhere(['basic_state' => mWikiBasic::STATE_ONLINE, 'store_id' => $storeId]);
        $basicIds = array_column($basicWikiList, 'id');
        $basicWikiList = array_column($basicWikiList, null, 'id');
        $spuList = mWiki::selectByWhere([
            'store_id' => $storeId,
            'is_default' => 1,
            'status[!]' => mWiki::STATUS_DEL,
            'basic_id' => $basicIds,
            'is_official' => 1,
        ]);
        $spuList = array_column($spuList, null, 'basic_id');
        foreach ($categoryWikiList as $row) {
            $basicId = $row['basic_id'];
            $wikiSpuInfo = isset($spuList[$basicId]) ? $spuList[$basicId] : [];
            if ($wikiSpuInfo) {
                if (isset($basicWikiList[$basicId])) {
                    $result[$basicId] = [
                        'spu_id' => $wikiSpuInfo['id'],
                        'wiki_title' => $basicWikiList[$basicId]['title'],
                        'spu_title' => $wikiSpuInfo['title'],
                        'wiki_id' => $wikiSpuInfo['basic_id'],
                        'sort' => $row['sort'],
                        'custom_state' => $row['custom_state'],
                        'cover_img' => $wikiSpuInfo['cover_img'],
                    ];
                }
            }
        }
        if ($categoryId == 0) {
            foreach ($spuList as $basicId => $row) {
                if (isset($spuList[$basicId]) && isset($basicWikiList[$basicId]) && !isset($result[$basicId])) {
                    $result[$basicId] = [
                        'spu_id' => $row['id'],
                        'wiki_title' => $basicWikiList[$basicId]['title'],
                        'spu_title' => $row['title'],
                        'wiki_id' => $row['basic_id'],
                        'sort' => 0,
                        'custom_state' => 0,
                        'cover_img' => $row['cover_img'],
                    ];
                }
            }
        }

        return $result;
    }

    /**
     * 商品列表搜索
     * @param int $storeId
     * @param int $categoryId
     * @param string $title
     * @return array
     */
    public static function searchCategoryWiki(int $storeId, int $categoryId = 0, string $title = ''): array
    {
        $result = [];
        $basicWhere = ['basic_state' => mWikiBasic::STATE_ONLINE, 'store_id' => $storeId];
        if (!empty($title)) {
            if (is_numeric($title)) {
                $basicWhere['id'] = $title;
            } else {
                $basicWhere['title[~]'] = $title;
            }
        }
        $basicWikiList = mWikiBasic::selectByWhere($basicWhere);
        $basicIds = array_column($basicWikiList, 'id');
        $basicWikiList = array_column($basicWikiList, null, 'id');

        $categoryWikiList = mCustomCategoryWiki::selectByWhere([
            'category_id' => $categoryId,
            'store_id' => $storeId,
            'custom_state' => mCustomCategoryWiki::STATE_NORMAL,
            'ORDER' => ['sort' => 'ASC', 'id' => 'DESC'],
        ]);
        $spuList = mWiki::selectByWhere([
            'store_id' => $storeId,
            'is_default' => 1,
            'status[!]' => mWiki::STATUS_DEL,
            'basic_id' => $basicIds,
            'is_official' => 1,
        ]);
        $spuList = array_column($spuList, null, 'basic_id');
        foreach ($categoryWikiList as $row) {
            $basicId = $row['basic_id'];
            $wikiSpuInfo = isset($spuList[$basicId]) ? $spuList[$basicId] : [];
            if ($wikiSpuInfo) {
                if (isset($basicWikiList[$basicId])) {
                    $result[$basicId] = [
                        'spu_id' => $wikiSpuInfo['id'],
                        'wiki_title' => $basicWikiList[$basicId]['title'],
                        'spu_title' => $wikiSpuInfo['title'],
                        'wiki_id' => $wikiSpuInfo['basic_id'],
                        'sort' => $row['sort'],
                        'custom_state' => $row['custom_state'],
                        'cover_img' => $wikiSpuInfo['cover_img'],
                    ];
                }
            }
        }
        foreach ($spuList as $basicId => $row) {
            if (isset($spuList[$basicId]) && isset($basicWikiList[$basicId]) && !isset($result[$basicId])) {
                $result[$basicId] = [
                    'spu_id' => $row['id'],
                    'wiki_title' => $basicWikiList[$basicId]['title'],
                    'spu_title' => $row['title'],
                    'wiki_id' => $row['basic_id'],
                    'sort' => 0,
                    'custom_state' => 0,
                    'cover_img' => $row['cover_img'],
                ];
            }
        }

        return $result;
    }

    /**
     * 获取商品列表
     * @param $storeId
     * @param int $categoryId
     * @param int $pageSize
     * @param int $page
     * @return array
     * @throws \Exception
     */
    public static function getWikiByStoreId($storeId, int $categoryId = 0, int $pageSize = 20, int $page = 1): array
    {
        $uid = StoreBasicService::getStoreUidById($storeId);
        $page = $page ? $page : 1;
        $limit = [
            ($page - 1) * $pageSize,
            $pageSize,
        ];
        $result = [];
        $count = 0;
        //获取当前分类下所有的商品basic
        $countCategoryWikiListWhere['store_id'] = $storeId;
        $countCategoryWikiListWhere['custom_state'] = StoreCustomCategoryWiki::STATE_NORMAL;
        $countCategoryWikiListWhere['category_id'] = $categoryId;
        $countCategoryWikiList = StoreCustomCategoryWiki::selectByWhere($countCategoryWikiListWhere);
        $basicIds = array_unique(array_column($countCategoryWikiList, 'basic_id'));
        //根据当前分类下的basic_id 集合 过滤此集合内已下线的数据
        $categoryWikiListInfo = $basicIds ? mWikiBasic::selectByWhere([
            'basic_state' => mWikiBasic::STATE_ONLINE,
            'store_id' => $storeId,
            'id' => $basicIds,
        ]) : [];
        //获取上线的basic_id 集合
        $basicIds = array_column($categoryWikiListInfo, 'id');
        //已上线的basic总数
        if ($basicIds) {
            $count = count($basicIds);
            $categoryWikiWhere['store_id'] = $storeId;
            $categoryWikiWhere['basic_id'] = $basicIds;
            $categoryWikiWhere['category_id'] = $categoryId;
            $categoryWikiWhere['custom_state'] = StoreCustomCategoryWiki::STATE_NORMAL;
            $categoryWikiWhere['ORDER'] = ['sort' => 'ASC', 'id' => 'DESC'];
            $categoryWikiWhere['LIMIT'] = $limit;
            $categoryWikiList = StoreCustomCategoryWiki::selectByWhere($categoryWikiWhere);
            $basicIds = array_column($categoryWikiList, 'basic_id');
            if ($basicIds) {
                $basicIds = mWikiBasic::selectByWhere([
                    'basic_state' => mWikiBasic::STATE_ONLINE,
                    'store_id' => $storeId,
                    'id' => $basicIds,
                ], 'id');
            }
            $result = self::getStoreWikiListByBasicIds($storeId, $basicIds, $uid);
        }

        return ['list' => array_values($result), 'is_over' => $count < ($page * $pageSize) ? 1 : 0, 'total' => $count];
    }

    private static function getStoreWikiListByBasicIds($storeId, $basicIds, $uid)
    {
        $list = [];
        if ($storeId && $basicIds) {
            //grpc 调用
            $wikiGrpcClient = \Wiki\GrpcClient::getInstance();
            $aRet = $wikiGrpcClient->getStoreWikiListByBasicIds([
                "storeId" => $storeId,
                'basicIds' => $basicIds,
                "fieldsGroup" => Infos::FIELDS_GROUP_LIST,
                "uid" => $uid,
            ]);

            if ($aRet['biz_code'] != 0) {
                return [];
            }
            $list = $aRet['result']['list'] ?? [];
            $list = array_values($list);
            $list = $list ? array_column($list, null, 'basic_id') : [];
        }
        return $list;
    }
}